package net.FamilyTree.controller;


import net.FamilyTree.entity.People;
import net.FamilyTree.form.SearchForm;
import net.FamilyTree.service.PeopleService;
import net.FamilyTree.util.ResultVoUtil;
import net.FamilyTree.vo.ResultVo;
import net.FamilyTree.vo.TreeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/people")
public class PeopleController {
    @Autowired
    private PeopleService peopleService;

    // 添加人员信息
    @PostMapping("/save")
    public ResultVo save(@RequestBody People people) {
        // 调用PeopleService的add方法添加人员信息
        Boolean add = this.peopleService.add(people);
        if (!add) {
            return ResultVoUtil.fail();
        }
        return ResultVoUtil.success(null);
    }

    // 获取人员列表
    @GetMapping("/list/{page}/{size}")
    public ResultVo list(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        // 调用PeopleService的list方法获取人员列表
        return ResultVoUtil.success(this.peopleService.list(page, size));
    }

    // 根据条件搜索人员
    @GetMapping("/search")
    public ResultVo search(SearchForm searchForm) {
        // 调用PeopleService的search方法进行人员搜索
        return ResultVoUtil.success(this.peopleService.search(searchForm));
    }

    // 根据人员ID获取人员信息
    @GetMapping("/findById/{id}")
    public ResultVo findById(@PathVariable("id") Integer id) {
        // 调用PeopleService的getById方法根据ID获取人员信息
        People byId = this.peopleService.getById(id);
        return ResultVoUtil.success(byId);
    }

    // 更新人员信息
    @PutMapping("/update")
    public ResultVo update(@RequestBody People people) {
        // 调用PeopleService的update方法更新人员信息
        Boolean update = this.peopleService.update(people);
        if(!update){
            return ResultVoUtil.fail();
        }
        return ResultVoUtil.success(null);
    }

    // 删除人员信息
    @DeleteMapping("/deleteById/{id}")
    public ResultVo deleteById(@PathVariable("id") Integer id){
        // 调用PeopleService的delete方法删除人员信息
        Boolean delete = this.peopleService.delete(id);
        if(!delete){
            return ResultVoUtil.fail();
        }
        return ResultVoUtil.success(null);
    }

    // 获取所有人员列表
    @GetMapping("/allList")
    public ResultVo allList(){
        // 调用PeopleService的list方法获取所有人员列表
        List<People> peopleList = this.peopleService.list();
        return ResultVoUtil.success(peopleList);
    }

    // 获取人员树形结构
    @GetMapping("/treeJson")
    public ResultVo treeJson() {
        // 调用PeopleService的list方法获取所有人员列表
        List<People> peopleList = this.peopleService.list();
        List<TreeVO> dataList = new ArrayList<>();
        // 将人员列表转换为树形结构数据
        for(People people : peopleList) {
            TreeVO treeVO = new TreeVO();
            treeVO.setId(people.getId());
            treeVO.setParentId(people.getParentId());
            treeVO.setName(people.getName());
            treeVO.setImage_url(people.getImage());
            dataList.add(treeVO);
        }
        // 构建树形结构
        List<TreeVO> departmentList = new ArrayList<>();
        for (TreeVO child : dataList) {
            if (child.getParentId() == 0 ) {
                departmentList.add(child);
            } else {
                for (TreeVO parent : dataList) {
                    if (child.getParentId().equals(parent.getId())) {
                        // 组合父子节点的关系
                        parent.getChildren().add(child);
                    }
                }
            }
        }
        return ResultVoUtil.success(departmentList);
    }

    // 文件上传
    @PostMapping("/file/addFile")
    public ResultVo addFile(MultipartFile file){
        // 调用uploadFile方法将文件保存到本地并返回文件URL
        String imageUrl = uploadFile(file);
        return ResultVoUtil.success(imageUrl);
    }

    // 文件上传，保存到本地
    private String uploadFile(MultipartFile file){
        try {
            // 设置文件保存目录
            Calendar calendar = Calendar.getInstance();
            String yearMonth = calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1);
            String filePath = "E:\\upload\\" + yearMonth;

            // 创建文件目录
            File realPath = new File(filePath);
            if (!realPath.exists()){
                boolean mkdirs = realPath.mkdirs();
            }

            // 设置文件名
            String fileRealName = file.getOriginalFilename();
            String suffix = fileRealName.substring(fileRealName.lastIndexOf(".") + 1);
            String fileName = "file-" + UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;

            // 保存文件
            file.transferTo(new File(realPath + "/" + fileName));

            // 返回文件URL
            String fileUrl = "/upload/" + yearMonth + "/" +fileName;
            return "http://localhost:8081" + fileUrl;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

